package com.bc.plugin.doc.base.impl;

import com.bc.plugin.doc.base.IUsageDataRepository;
import com.bc.plugin.doc.dto.UsageDataDTO;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.power.common.util.FileUtil;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class FileUsageDataRepository implements IUsageDataRepository {

    public static final String DEFAULT_DATA_FILE_PATH = "target/doc/data.json";
    private Map<String, UsageDataDTO> dataMap;
    private String filePath;

    public FileUsageDataRepository() {
        this(DEFAULT_DATA_FILE_PATH);
    }

    public FileUsageDataRepository(String dataFile) {
        this.filePath = dataFile;
        File file = new File(dataFile);
        try {
            if (file.exists()) {
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                List<UsageDataDTO> list = gson.fromJson(new FileReader(file), new TypeToken<List<UsageDataDTO>>() {
                }.getType());
                dataMap = list.stream().collect(Collectors.toMap(UsageDataDTO::getUrl, item -> item));
            } else {
                dataMap = new HashMap<>();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public UsageDataDTO findByUrl(String url) {
        return dataMap.get(url);
    }

    @Override
    public void save(UsageDataDTO exampleDataDTO) {
        dataMap.put(exampleDataDTO.getUrl(), exampleDataDTO);
        Collection<UsageDataDTO> list = dataMap.values();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String fileContent = gson.toJson(list);
        FileUtil.nioWriteFile(fileContent, filePath);
    }

}
